/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-06-06 10:33:36
 * @LastEditTime: 2022-07-17 23:20:10
 * @LastEditors: liutq
 * @Reference:
 */
package goods

import (
	"errors"

	"github.com/maxyang107/jinglan/common"
	"github.com/maxyang107/jinglan/model"
)

type Irrigation struct {
	ID            uint `gorm:"column:id; parimary_key" json:"id"`
	GoodsId       uint `gorm:"column:goods_id;" json:"goods_id"`
	IrrigationNum uint `gorm:"column:irrigation_num;" json:"irrigation_num"`
}

type IrrigationInfo struct {
	ID            uint   `gorm:"column:id; parimary_key" json:"id"`
	GoodsId       uint   `gorm:"column:goods_id;" json:"goods_id"`
	GoodsName     string `gorm:"column:goods_name;" json:"goods_name"`
	IrrigationNum uint   `gorm:"column:irrigation_num;" json:"irrigation_num"`
}
type IrrigationList struct {
	Page uint

	PerPage uint

	List []IrrigationInfo

	Total uint
}

func UpdateIrrigation(param common.Irrigation) error {
	if param.ID > 0 {
		if err := model.Db.Model(&Irrigation{}).Update(&param).Error; err != nil {
			return err
		}
		return nil
	}

	var tmp Irrigation
	model.Db.Where(&Irrigation{GoodsId: param.GoodsId}).First(&tmp)
	if tmp.ID > 0 {
		return errors.New("该商品已设置过灌水，请在现有记录增加")
	}
	model.Db.Create(&param)
	return nil
}

func GetIrrigation(goodsid uint) *IrrigationInfo {
	var res IrrigationInfo
	var tmp Irrigation
	model.Db.Where(&Irrigation{GoodsId: goodsid}).First(&tmp)

	if tmp.ID == 0 {
		tmp.GoodsId = goodsid
		tmp.IrrigationNum = 0
		model.Db.Create(&tmp)
	}
	model.Db.Table("goods").Select("irrigation.*,goods.goods_name").Joins("inner join irrigation on irrigation.goods_id = goods.id").Where(&Goods{ID: goodsid}).First(&res)
	return &res
}
func GetIrrigationList(param_ common.AdminGoodsList) *IrrigationList {
	var resp_ IrrigationList
	resp_.Total = getIrrigationTotal(param_)

	model.Db.Table("goods").Select("irrigation.*,goods.goods_name").Joins("inner join irrigation on irrigation.goods_id = goods.id").Limit(param_.PerPage).Offset((param_.Page - 1) * param_.PerPage).Scan(&resp_.List)
	resp_.Page = param_.Page
	resp_.PerPage = param_.PerPage

	return &resp_
}

func getIrrigationTotal(query_ common.AdminGoodsList) uint {
	var total uint
	model.Db.Model(&Irrigation{}).Count(&total)

	return total
}
